import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import Upload from 'rc-upload';

import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Checkbox,
  Radio,
  Badge,
  Divider,
} from 'antd';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const confirm = Modal.confirm;
import DescriptionList from 'components/DescriptionList';
const { Description } = DescriptionList;
const RadioGroup = Radio.Group;

import { articleAdd, articleUpdate } from '../../services/api';
import { getArrFromObj, getToken, getCurrent } from '../../utils/utils';
import config from '../../common/config';

import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './achievementList.less';

import uploadPng from '../../assets/upload.png';

const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const PAGE_STATUS_MAP = {
  '0': '无效',
  '1': '有效',
};

const PAGE_STATUS_ARR = getArrFromObj(PAGE_STATUS_MAP);

const PAGE_CATEGORY_MAP = {
  1: '新闻动态',
  2: '政策资讯',
  3: '知产干货',
  4: '关于我们',
};

const PAGE_CATEGORY_ARR = getArrFromObj(PAGE_CATEGORY_MAP);

const PAGE_SIZE = 10;

@connect(({ achievementList, loading }) => {
  return {
    achievementList,
    loading: loading.models.achievementList,
  };
})
@Form.create()
export default class List extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    id: null,

    title: null,
    status: '1',
    category: '1',
    author: getCurrent().username,

    pcTitle: null,
    pcKeywords: null,
    pcDesc: null,
    mobileTitle: null,
    mobileKeywords: null,
    mobileDesc: null,
    content: '',

    imgOptions: {},
    coverUrl: null,
  };

  componentDidMount() {
    this.getImgOptions();
    this.init();
  }

  getImgOptions() {
    const token = getToken();

    const imgOptions = {
      action: config.serveraddress + '/upload/putObject?dataType=0',
      data: { dataType: 0 },
      headers: {
        Authorization: 'Bearer ' + token,
      },
      multiple: false,
      beforeUpload(file) {
        console.log('beforeUpload', file.name);
      },
      onStart: file => {
        console.log('onStart', file.name);
      },
      onProgress(step, file) {},
    };

    this.setState({
      imgOptions,
    });
  }

  init() {
    const { dispatch } = this.props;
    dispatch({
      type: 'achievementList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'achievementList/queryList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'achievementList/queryList',
      payload: {
        pageNum: 1,
        pageSize: PAGE_SIZE,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (!fieldsValue.title) {
        delete fieldsValue.title;
      }
      if (!fieldsValue.expertscompleting) {
        delete fieldsValue.expertscompleting;
      }

      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize: PAGE_SIZE,
      };

      dispatch({
        type: 'achievementList/queryList',
        payload: values,
      });
    });
  };

  handleShowModal = e => {
    e.preventDefault();
    this.setState({
      id: null,
      modalVisible: true,
      levelRule: '',
      name: '',
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  async handleSave(e) {
    const {
      title,
      status,
      category,
      author,
      coverUrl,
      pcTitle,
      pcKeywords,
      pcDesc,
      mobileTitle,
      mobileKeywords,
      mobileDesc,
      content,
    } = this.state;
    if (!title) {
      return message.error('请填写文章标题');
    }

    if (!author) {
      return message.error('请填写文章作者');
    }

    if (!category) {
      return message.error('请选择文章分类');
    }

    if (!content) {
      return message.error('请填写文章内容');
    }

    await this.doSave();
  }

  async doSave() {
    const { dispatch } = this.props;

    const {
      id,
      title,
      status,
      category,
      author,
      coverUrl,
      pcTitle,
      pcKeywords,
      pcDesc,
      mobileTitle,
      mobileKeywords,
      mobileDesc,
      content,
    } = this.state;

    let response = {};
    if (id) {
      const params = {
        id,
        title,
        status,
        category,
        author,
        coverUrl,
        pcTitle,
        pcKeywords,
        pcDesc,
        mobileTitle,
        mobileKeywords,
        mobileDesc,
        content: content.toHTML(),
      };
      response = await articleUpdate(params);
    } else {
      const params = {
        title,
        status,
        category,
        author,
        coverUrl,
        pcTitle,
        pcKeywords,
        pcDesc,
        mobileTitle,
        mobileKeywords,
        mobileDesc,
        content: content.toHTML(),
      };
      response = await articleAdd(params);
    }

    if (response.code === 200) {
      this.setState({
        modalVisible: false,
      });

      this.init();
    } else {
      message.error(response.message);
    }
  }

  handleReply(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  handleOnchange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  onChange(field, value, dateString) {
    this.setState({
      [field]: dateString,
    });
  }

  handleSelectOnchange(field, value) {
    this.setState({
      [field]: value,
    });
  }

  onRadioChange(field, e) {
    this.setState({
      [field]: e.target.value,
    });
  }

  handleView(item) {
    this.setState({
      ...item,
      modalVisible: true,
    });
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="">
              {getFieldDecorator('title')(<Input placeholder="成果名称" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="">
              {getFieldDecorator('expertscompleting')(<Input placeholder="发明人" />)}
            </FormItem>
          </Col>

          <Col md={4} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" onClick={this.handleSearch.bind(this)}>
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  handleEditorChange = editorState => {
    this.setState({
      content: editorState,
    });
  };

  uploadSuccess(res, field) {
    this.setState({
      [field]: res.data,
    });
  }

  uploadError(res, field) {
    debugger;
  }

  render() {
    let { achievementList: { data }, loading } = this.props;
    const { getFieldDecorator } = this.props.form;
    const { selectedRows, modalVisible, imgOptions, coverUrl } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        render: (val, item, index) => (
          <span>{(data.pagination.current - 1) * data.pagination.pageSize + index + 1}</span>
        ),
      },
      {
        title: '成果名称',
        ellipsis: true,
        width: 100,
        dataIndex: 'title',
      },
      {
        title: '归属高校',
        dataIndex: 'colleges',
      },
      {
        title: '成果发明人',
        dataIndex: 'expertscompleting',
      },
      {
        title: '操作',
        dataIndex: '',
        width: 50,
        render: (val, item) => (
          <span>
            <a href="javascript:;" onClick={this.handleView.bind(this, item)}>
              查看
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderLayout title="成果管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTable
              disableSelect={true}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        <Modal
          maskClosable={false}
          width="70%"
          title="成果详情"
          footer={null}
          visible={this.state.modalVisible}
          onOk={this.handleSave.bind(this)}
          onCancel={this.handleCancel.bind(this)}
        >
          <Row style={{ marginTop: 10, marginBottom: 20 }}>
            <Col span={24}>
              <div style={{ textAlign: 'center', fontWeight: 'bold' }}>{this.state.title}</div>
            </Col>
          </Row>
          <Row style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>
              <div style={{ textAlign: 'center' }}>{this.state.colleges}</div>
            </Col>
          </Row>
          <Row style={{ marginTop: 10, marginBottom: 20 }}>
            <Col span={24}>
              <div style={{ textAlign: 'center' }}>发明人: {this.state.expertscompleting}</div>
            </Col>
          </Row>

          <Divider orientation="left">综合介绍</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 48 }} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>{this.state.abstractDesc}</Col>
          </Row>

          <Divider orientation="left">应用方向</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>{this.state.category}</Col>
          </Row>

          <Divider orientation="left">专利情况</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>-</Col>
          </Row>

          <Divider orientation="left">创新要点</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>-</Col>
          </Row>

          <Divider orientation="left">技术指标</Divider>

          <Row gutter={{ md: 24, lg: 24, xl: 24 }} style={{ marginTop: 10, marginBottom: 10 }}>
            <Col span={24}>-</Col>
          </Row>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
